package cn.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

//@WebFilter

public class RoleFilter implements Filter {
	public RoleFilter() {
		System.out.println("RoleFilter实例化");
	}

	@Override
	public void destroy() {
		System.out.println("销毁");
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("进入了登录验证过滤器");
		try {
			HttpServletRequest request = (HttpServletRequest) arg0;
			String path = request.getServletPath();
			System.out.println("当前地址：" + path);
			if (path.equals("/doLogin.jsp") || path.equals("/login.jsp") || path.equals("/logout.jsp")
					|| path.equals("/vcodeServlet") || path.endsWith(".js") || path.endsWith(".css")) {
				arg2.doFilter(request, arg1);// 放行
				return;
			}
			if (request.getSession().getAttribute("USER_LOGIN") == null) {

				request.setAttribute("msg", "您还没有登录，不能访问！");
				request.getRequestDispatcher("/login.jsp").forward(request, arg1);
				// PrintWriter out = arg1.getWriter();
				// out.print("<script>alert('您没有登录，无权访问');history.back();</script>");
				return;
			}

			arg2.doFilter(request, arg1);// 放行
		} finally {
			System.out.println("离开了登录验证过滤器");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("RoleFilter初始化");
	}

}
